# -*- coding: utf-8 -*-
import os
import sys
import subprocess
from PyQt5.QtCore import QThread, pyqtSignal, Qt
from TcpUdpClient import MainWindow as TcpUdpClientWindow
from TcpUdpServer import MainWindow as TcpUdpServerWindow
from UserManagement import UserManagementApp  # 导入用户管理窗口
from login_window import LoginWindow  # 导入FTP登录窗口
from server import FTPGUI, FTPServer, HOST, PORT # 导入FTP服务器相关
import threading # 用于FTP服务器线程
# 假设 mainFTP.py 中有一个主函数或类，例如 main_ftp_start
# from mainFTP import main_ftp_start  # 或者具体的类名
# 假设 server.py 中有一个主函数或类，例如 start_ftp_server
# from server import start_ftp_server  # 或者具体的类名

# 为了能直接调用，需要知道 mainFTP.py 和 server.py 的入口点
from login_window import LoginWindow  # mainFTP.py 实际上是启动 login_window
from server import FTPServer, ServerThread, HOST, PORT, BASE_DIR # 导入FTPServer类、ServerThread类和相关常量
from PyQt5.QtWidgets import QApplication # 需要QApplication来运行LoginWindow
import threading # 用于在后台运行FTP服务器
from PyQt5.QtWidgets import QApplication, QMainWindow, QTabWidget, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, \
    QPushButton, QTextEdit, QFileDialog, QListWidget, QMessageBox


# 自定义线程类，用于运行外部脚本
class ScriptThread(QThread):
    # 定义一个信号，用于输出脚本的执行结果
    output_signal = pyqtSignal(str)

    def __init__(self, script_path):
        super().__init__()
        self.script_path = script_path

    def run(self):
        try:
            # 使用 subprocess.Popen 运行脚本
            process = subprocess.Popen(
                ["python", self.script_path],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
            )

            # 实时读取脚本输出
            while True:
                output = process.stdout.readline()
                if output == "" and process.poll() is not None:
                    break
                if output:
                    self.output_signal.emit(output.strip())

            # 读取错误输出
            stderr = process.stderr.read()
            if stderr:
                self.output_signal.emit(f"Error: {stderr.strip()}")

        except Exception as e:
            self.output_signal.emit(f"Exception: {str(e)}")

class TCPUDPTab(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()

        # Mode selection
        mode_layout = QHBoxLayout()
        self.client_radio = QPushButton("客户端")
        self.client_radio.clicked.connect(self.run_script)
        self.server_radio = QPushButton("服务端")
        self.server_radio.clicked.connect(self.run_Tcp_Udp_Server)
        mode_layout.addWidget(self.client_radio)
        mode_layout.addWidget(self.server_radio)
        layout.addLayout(mode_layout)

        # IP and Port input
        ip_port_layout = QHBoxLayout()
        self.ip_input = QLineEdit()
        self.ip_input.setPlaceholderText("IP Address")
        self.port_input = QLineEdit()
        self.port_input.setPlaceholderText("Port")
        # ip_port_layout.addWidget(self.ip_input)
        # ip_port_layout.addWidget(self.port_input)
        layout.addLayout(ip_port_layout)

        # Message input and send button
        message_layout = QHBoxLayout()
        self.message_input = QLineEdit()
        self.message_input.setPlaceholderText("Enter message")
        self.send_button = QPushButton("Send")
        # message_layout.addWidget(self.message_input)
        # message_layout.addWidget(self.send_button)
        layout.addLayout(message_layout)

        # Message display area
        self.message_display = QTextEdit()
        self.message_display.setHtml("""
            <h3 style="color: #2E86C1;">TCP/UDP测试方式</h3>
            <ol>
                <li style="color: #148F77; font-weight: bold;">
                    点击“服务端”按钮；
                </li>
                 <li style="color: #148F77; font-weight: bold;">
                    选择协议类型(TCP/UDP)，选择具体网卡IP、本地端口，点击“连接网络”；
                </li>
                <li style="color: #148F77; font-weight: bold;">
                    点击“客户端”按钮；
                </li>
                <li style="color: #148F77; font-weight: bold;">
                    选择协议类型(TCP/UDP)，输入目标IP、目标端口，点击“连接网络”。
                </li>
            </ol>
        """)
        self.message_display.setReadOnly(True)
        layout.addWidget(self.message_display)

        self.setLayout(layout)

    def run_script(self):
        # 直接创建并显示 TcpUdpClient 窗口
        # 注意：这里假设 TcpUdpClientWindow 不需要特殊的父窗口或参数
        # 如果需要，您可能需要调整实例化过程
        self.client_window = TcpUdpClientWindow()
        # 如果 TcpUdpClient.py 中有 qss 样式设置，确保路径正确或在此处重新应用
        # 例如: 
        # styleFile_client = os.path.join(os.path.dirname(__file__), "Style/qss/flat_white.qss")
        # if os.path.exists(styleFile_client):
        #     with open(styleFile_client, "r") as f:
        #         qssStyle_client = f.read()
        #     self.client_window.setStyleSheet(qssStyle_client)
        self.client_window.show()

        # 原来的线程逻辑可以移除或注释掉，如果不再需要 ScriptThread
        # self.thread = ScriptThread("TcpUdpClient.py")
        # # self.thread.output_signal.connect(self.update_output)
        # self.thread.start()
    def run_Tcp_Udp_Server(self):
        # 直接创建并显示 TcpUdpServer 窗口
        self.server_window = TcpUdpServerWindow()
        # 如果 TcpUdpServer.py 中有 qss 样式设置，确保路径正确或在此处重新应用
        # 例如:
        # styleFile_server = os.path.join(os.path.dirname(__file__), "Style/qss/flat_white.qss")
        # if os.path.exists(styleFile_server):
        #     with open(styleFile_server, "r") as f:
        #         qssStyle_server = f.read()
        #     self.server_window.setStyleSheet(qssStyle_server)
        self.server_window.show()

        # 原来的线程逻辑可以移除或注释掉
        # self.thread = ScriptThread("TcpUdpServer.py")
        # # self.thread.output_signal.connect(self.update_output)
        # self.thread.start()

    def update_output(self, text):
        # 更新输出显示区域
        self.output_display.append(text)

class FTPTab(QWidget):
    def __init__(self):
        super().__init__()
        self.status_label = None

        self.initUI()
        self.worker_thread = None  # 用于保存线程对象

    def initUI(self):
        layout = QVBoxLayout()
        self.user_manage = QPushButton("FTP服务端用户管理")
        self.user_manage.clicked.connect(self.run_user_management)
        layout.addWidget(self.user_manage)
        # Mode selection
        mode_layout = QHBoxLayout()
        self.client_radio = QPushButton("客户端")
        self.client_radio.clicked.connect(self.run_FTP_Client)
        self.server_radio = QPushButton("启动 FTP 服务端")
        self.server_radio.clicked.connect(self.run_FTP_Server)


        mode_layout.addWidget(self.client_radio)
        mode_layout.addWidget(self.server_radio)
        # 创建标签，用于显示状态
        # self.status_label = QLabel('FTP服务端状态：未启动', self)
        # layout.addWidget(self.status_label)

        layout.addLayout(mode_layout)

        # File selection
        file_layout = QHBoxLayout()
        self.file_input = QLineEdit()
        self.file_input.setPlaceholderText("Select file")
        self.browse_button = QPushButton("Browse")
        file_layout.addWidget(self.file_input)
        file_layout.addWidget(self.browse_button)
        # layout.addLayout(file_layout)

        # File list and transfer button
        self.file_list = QListWidget()
        self.transfer_button = QPushButton("Transfer")
        # layout.addWidget(self.file_list)
        # layout.addWidget(self.transfer_button)

        self.message_display = QTextEdit(self)
        self.message_display.setHtml("""
                   <h3 style="color: #2E86C1;">FTP服务端用户权限</h3>
                   <ol>
                       <li style="color: #148F77; font-weight: bold;">
                           管理员：全权限（包括查看、删除、创建）文件，可访问所有路径；
                       </li>
                       <li style="color: #148F77; font-weight: bold;">
                           普通用户：仅可读。
                       </li>
                   </ol>
               """)
        self.message_display.setReadOnly(True)
        layout.addWidget(self.message_display)
        # Log display area
        self.log_display = QTextEdit()
        self.log_display.setReadOnly(True)
        self.setLayout(layout)
    def run_user_management(self):
        # 直接创建并显示 UserManagementApp 窗口
        if not hasattr(self, 'user_management_window') or not self.user_management_window.isVisible():
            self.user_management_window = UserManagementApp()
            self.user_management_window.show()
        else:
            self.user_management_window.activateWindow()
            self.user_management_window.raise_()

    def update_output(self, text):
        # 更新输出显示区域
        self.output_display.append(text)
    def run_FTP_Client(self):
        # 直接调用 mainFTP.py 中的逻辑
        # 这是一个示例调用，您需要根据 mainFTP.py 的实际结构来修改
        # 例如，如果 mainFTP.py 有一个 main() 函数或者一个启动类
        try:
            # 假设 mainFTP.py 的主要逻辑封装在一个函数或类中
            # 如果 mainFTP.py 是一个完整的PyQt应用，它应该有一个启动方式
            # 例如，它可能有一个类似 QApplication 和主窗口的设置
            # mainFTP.py 的主要逻辑是启动 LoginWindow
            # 我们直接实例化并显示 LoginWindow
            if not hasattr(self, 'login_window_ftp') or not self.login_window_ftp.isVisible():
                self.login_window_ftp = LoginWindow()
                self.login_window_ftp.show()
            else:
                self.login_window_ftp.activateWindow() # 如果已存在，则激活窗口
                self.login_window_ftp.raise_() # 将窗口置于顶层

        except Exception as e:
            print(f"Error running FTP Client: {e}")
            QMessageBox.critical(self, "错误", f"启动FTP客户端失败: {e}")

    def run_FTP_Server(self):
        # 使用 ServerThread 类来启动 FTP 服务器
        try:
            # 检查是否已经有服务器线程在运行
            if not hasattr(self, 'ftp_server_thread'):
                # 创建 ServerThread 实例
                self.ftp_server_thread = FTPGUI()
                self.ftp_server_thread.show()
        except Exception as e:
            print(f"Error running FTP Server: {e}")
            QMessageBox.critical(self, "错误", f"启动FTP服务器失败: {e}")

    def update_log(self, message):
        """更新日志内容"""
        print("接收到消息：", message)
        self.message_display.append(message)  # 在日志控件中追加新消息

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle("网络测试工具")
        self.setGeometry(100, 100, 800, 600)

        # Create tabs
        self.tabs = QTabWidget()
        self.tcp_udp_tab = TCPUDPTab()
        self.ftp_tab = FTPTab()

        self.tabs.addTab(self.tcp_udp_tab, "TCP/UDP")
        self.tabs.addTab(self.ftp_tab, "FTP")

        self.setCentralWidget(self.tabs)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())